package HashPackage2;

import java.util.HashMap;

/**
 * @author Lzm
 * @version 1.0
 */
public class twoSum_ {

  // 遍历nums, 每遍历到nums中的一个元素, 就要判断tar - nums[i]是否存在于map中
  public int[] twoSum(int[] nums, int target) {
    if (nums.length == 2){
      if (nums[0] + nums[1] != target){
        return new int[2];
      }else{
        return new int[]{0,1};
      }
    }
    HashMap<Integer,Integer> map = new HashMap();
    for (int i = 0; i < nums.length; i++) {
      if (map.containsKey(target - nums[i])){
        return new int[]{i,map.get(target-nums[i])};
      }
      else {
        map.put(nums[i],i);
      }
    }
    return new int[2];
  }
}
